package user_handler

import (
	"net/http"

	"bird/internal/pkg/code"
	"bird/internal/pkg/core"
	"bird/pkg/errno"
)

type tokenRequest struct {
	TokenType    *int    `form:"token_type" binding:"required"`
	PhoneNo      string `form:"phone_no" binding:"omitempty,len=11"`
	VerifyCode   string    `form:"verify_code" binding:"omitempty"`
	AccessToken  string `form:"access_token"`
	RefreshToken string `form:"refresh_token"`
}

type tokenResponse struct{}

// Token 获取&刷新
// @Summary 获取&刷新
// @Description 获取&刷新
// @Tags API.user
// @Accept json
// @Produce json
// @Param Request body tokenRequest true "请求信息"
// @Success 200 {object} tokenResponse
// @Failure 400 {object} code.Failure
// @Router /bird/api/token [post]
func (h *handler) Token() core.HandlerFunc {
	return func(c core.Context) {
		req := new(tokenRequest)
		res := new(tokenResponse)
		if err := c.ShouldBindForm(req); err != nil {
			c.AbortWithError(errno.NewError(
				http.StatusBadRequest,
				code.ParamBindError,
				code.Text(code.ParamBindError)).WithErr(err),
				)
			return
		}

		switch *req.TokenType {
		case 0:
			if err := h.userService.GenerateToken(c, req.PhoneNo, req.VerifyCode); err != nil {
				c.AbortWithError(errno.NewError(
					http.StatusOK,
					code.TokenLoginError,
					code.Text(code.TokenLoginError)).WithErr(err),
					)
				return
			}
		case 1:
			if err := h.userService.RefreshToken(c, req.AccessToken, req.RefreshToken); err != nil {
				c.AbortWithError(errno.NewError(
					http.StatusOK,
					code.TokenRefreshError,
					code.Text(code.TokenRefreshError)).WithErr(err),
				)
				return
			}
		}

		c.Payload(res)
	}
}
